package com.evaluation.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.evaluation.common.Result;
import com.evaluation.entity.Teacher;
import com.evaluation.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * PC端管理员登录控制器
 */
@RestController
@RequestMapping("/api/admin")
public class AdminLoginController {

    @Autowired
    private TeacherService teacherService;

    /**
     * 生成验证码图片
     */
    @GetMapping("/captcha")
    public void generateCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        // 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 生成4位数字验证码
        Random random = new Random();
        String captcha = String.format("%04d", random.nextInt(10000));
        
        // 将验证码存储到session中
        session.setAttribute("captcha", captcha);
        session.setAttribute("captchaTime", System.currentTimeMillis());

        // 创建图片
        int width = 120;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 填充背景色
        g.setColor(new Color(240, 240, 240));
        g.fillRect(0, 0, width, height);

        // 绘制边框
        g.setColor(new Color(200, 200, 200));
        g.drawRect(0, 0, width - 1, height - 1);

        // 添加干扰线
        g.setColor(new Color(180, 180, 180));
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        // 绘制验证码文字
        g.setFont(new Font("Arial", Font.BOLD, 24));
        for (int i = 0; i < captcha.length(); i++) {
            // 随机颜色，确保颜色可见（使用较暗的颜色以增强对比度）
            int r = random.nextInt(80) + 20; // 20-99
            int green = random.nextInt(80) + 20; // 20-99
            int blue = random.nextInt(80) + 20; // 20-99
            g.setColor(new Color(r, green, blue));
            
            // 计算字符位置
            int x = 20 + i * 20;
            int y = 25 + random.nextInt(10);
            
            // 随机旋转角度
            double angle = (random.nextDouble() - 0.5) * 0.4;
            g.rotate(angle, x, y);
            
            g.drawString(String.valueOf(captcha.charAt(i)), x, y);
            
            // 恢复旋转
            g.rotate(-angle, x, y);
        }

        g.dispose();

        // 使用ByteArrayOutputStream作为中间缓冲，避免ImageIO直接操作response的输出流
        // 这样可以避免应用关闭时StreamCloser线程出现NullPointerException
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "PNG", baos);
            byte[] imageBytes = baos.toByteArray();
            response.getOutputStream().write(imageBytes);
            response.getOutputStream().flush();
        } finally {
            // 关闭ByteArrayOutputStream
            try {
                baos.close();
            } catch (IOException e) {
                // 忽略关闭时的异常
            }
        }
    }

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> loginData, HttpSession session) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        String captcha = loginData.get("captcha");

        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error("用户名和密码不能为空");
        }

        if (StrUtil.isBlank(captcha)) {
            return Result.error("请输入验证码");
        }

        // 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captcha");
        Long captchaTime = (Long) session.getAttribute("captchaTime");
        
        if (sessionCaptcha == null || captchaTime == null) {
            return Result.error("验证码已过期，请刷新");
        }
        
        // 验证码5分钟有效期
        if (System.currentTimeMillis() - captchaTime > 5 * 60 * 1000) {
            session.removeAttribute("captcha");
            session.removeAttribute("captchaTime");
            return Result.error("验证码已过期，请刷新");
        }
        
        if (!sessionCaptcha.equalsIgnoreCase(captcha)) {
            return Result.error("验证码错误");
        }

        // 验证码使用后立即清除
        session.removeAttribute("captcha");
        session.removeAttribute("captchaTime");
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DLM", username).eq("MM", password);
        Teacher teacher = teacherService.getOne(queryWrapper);

        if (teacher == null) {
            return Result.error("用户名或密码错误");
        }

        // 检查教师状态
        if (!"0".equals(teacher.getJszt())) {
            return Result.error("该账号已被禁用");
        }

        // 检查权限类型
        String qxlx = teacher.getQxlx();
        if (!"0".equals(qxlx) && !"1".equals(qxlx)) {
            return Result.error("该用户没有系统访问权限");
        }

        // 设置session
        session.setAttribute("adminLogin", true);
        session.setAttribute("adminUser", username);
        session.setAttribute("teacherInfo", teacher);
        session.setAttribute("userType", qxlx); // 0：管理员 1：校领导
        session.setMaxInactiveInterval(7200); // 2小时超时

        Map<String, Object> result = new HashMap<>();
        result.put("userType", qxlx);
        result.put("userName", teacher.getJsxm());
        result.put("userRole", "0".equals(qxlx) ? "管理员" : "校领导");

        return Result.success("登录成功", result);
    }

    /**
     * 管理员退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        session.invalidate();
        return Result.success("退出成功");
    }

    /**
     * 检查登录状态
     */
    @GetMapping("/check")
    public Result<Map<String, Object>> checkLogin(HttpSession session) {
        Object adminLogin = session.getAttribute("adminLogin");
        String adminUser = (String) session.getAttribute("adminUser");
        Teacher teacherInfo = (Teacher) session.getAttribute("teacherInfo");

        if (adminLogin != null && adminUser != null && teacherInfo != null) {
            Map<String, Object> result = new HashMap<>();
            result.put("userType", teacherInfo.getQxlx());
            result.put("userName", teacherInfo.getJsxm());
            result.put("userRole", "0".equals(teacherInfo.getQxlx()) ? "管理员" : "校领导");
            return Result.success("已登录", result);
        } else {
            return Result.error("未登录");
        }
    }
}
